package com.help10000.rms.ui.base;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toolbar;

import com.amir.common.mvp.base.AbstractBaseActivity;
import com.amir.common.mvp.presenter.IPresenter;
import com.amir.common.mvp.view.IView;
import com.amir.common.utils.AppManager;
import com.amir.common.utils.Constant;
import com.amir.common.utils.DensityUtil;
import com.amir.common.utils.SPUtils;
import com.amir.common.utils.ToastUtil;
import com.gyf.barlibrary.ImmersionBar;
import com.help10000.rms.R;
import com.help10000.rms.ui.activitys.SelectCompanyActivity;
import com.help10000.rms.ui.activitys.logins.LoginActivity;
import com.help10000.rms.ui.utils.PageUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;

import org.jetbrains.annotations.Nullable;

import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.RequiresApi;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;


public abstract class BaseActivity<P extends IPresenter, V extends IView> extends AbstractBaseActivity<P, V> implements BGASwipeBackHelper.Delegate {
    protected BGASwipeBackHelper mSwipeBackHelper;
    protected Toolbar mToolbar;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        initSwipeBackFinish();
//        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        super.onCreate(savedInstanceState);


    }

    @Override
    public void onError(String string) {
        Message message = new Message();
        message.obj = string;
        message.what = 0;
        mHandler.sendMessage(message);

    }

    @Override
    public void onAgainLogin() {
        mHandler.sendEmptyMessage(1);
    }

    private BasePopupView basePopupView;

    @Override
    public void showDialog(@Nullable String mess, int code) {
        if (code == -2) {
            AppManager.getAppManager().finishAllActivity();
            PageUtils.Companion.jumpToActivity(this, LoginActivity.class);
        } else if (code == -3) {
            AppManager.getAppManager().finishAllActivity();
            PageUtils.Companion.jumpToActivity(this, SelectCompanyActivity.class);
        } else {
            if (basePopupView != null) {
                basePopupView.dismiss();
                basePopupView.destroy();
            }
            basePopupView = new XPopup.Builder(getViewContext())
                    .asConfirm("出错啦", mess, null, "确定", () -> {
                            }, null, true
                    ).show();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                ToastUtil.Companion.show("接口未正确响应");
            } else {

                SPUtils.Companion.remove(Constant.AccessToken);
                AppManager.getAppManager().finishAllActivity();
                startActivity(new Intent(mContext, LoginActivity.class));
            }
        }
    };

    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(false);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(false);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(false);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.5f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    public void setViewToolBar(View view) {
        // 判断api版本号是否大于等于21
        if (Build.VERSION.SDK_INT > 21) {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
            //            params.topMargin = DensityUtil.dip2px(mContext, BaseContents.TopHeight);
            params.topMargin = ImmersionBar.getStatusBarHeight(this) == 0 ? DensityUtil.dp2px(25) : ImmersionBar.getStatusBarHeight(this);
            view.setLayoutParams(params);
        }
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
        if (slideOffset > 0.5) {
//            overridePendingTransition(R.anim.anim_activity_trance_enter,R.anim.anim_activity_trance_exit);

        }
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {

    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {

//        BGAKeyboardUtil.closeKeyboard(this);
//        overridePendingTransition(R.anim.bga_sbl_activity_backward_enter, R.anim.bga_sbl_activity_backward_exit);
//        finish();
        mSwipeBackHelper.swipeBackward();
    }

    private Timer mTimer; // 计时器，每1秒执行一次任务
    private MyTimerTask mTimerTask; // 计时任务，判断是否未操作时间到达ns
    private long mLastActionTime; // 上一次操作时

    // 登录成功，开始计时
    protected void startTimer() {
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        // 初始化上次操作时间为登录成功的时间
        mLastActionTime = System.currentTimeMillis();
        // 每过1s检查一次
        mTimer.schedule(mTimerTask, 0, 1000);
        //Log.e(TAG, "登录成功开始计时");
    }

    // 每当用户接触了屏幕，都会执行此方法
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mLastActionTime = System.currentTimeMillis();
        //Log.e(TAG, "正在点击屏幕");
        return super.dispatchTouchEvent(ev);
    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //Log.e(TAG, "计时中……");
            // 5分钟未操作停止计时并退出登录
            if (System.currentTimeMillis() - mLastActionTime > 1000 * 60 * 1) {
                stopTimer();// 停止计时任务
            }
        }
    }

    // 停止计时任务
    public void stopTimer() {
        mTimer.cancel();
        //Log.e("", "取消计时");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
    //    @Override
//    public void onBackPressed() {
////        // 正在滑动返回的时候取消返回按钮事件
////        if (mSwipeBackHelper.isSliding()) {
////            return;
////        }
////        mSwipeBackHelper.backward();
//    }
}
